<template>
  <el-container>
    <el-form ref="resetForm" :model="resetForm" :rules="resetRules" label-width="80px" class="reset-form">
      <el-form-item label="设置密码" prop="password">
        <el-input v-model="resetForm.password" type="password" placeholder="请设置密码" maxlength="20" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="resetForm.confirmPassword" type="password" placeholder="请确认密码" maxlength="20" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleNextStep" style="margin-top: 20px;">确 认</el-button>
      </el-form-item>
    </el-form>
  </el-container>
</template>

<script>
import {getCodeImg} from "@/api/login";
import {setUserInfo} from "@/api/resetPassword";

export default {
  name: "setUserInfo",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.resetForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      codeUrl: "",
      resetForm: {
        userType: "COMP",
        username: "",
        password: "",
        confirmPassword: "",
      },
      resetRules:{
        userType: [{ required: true, trigger: "change", message: "请选择用户类型" }],
        userName: [{ required: true, trigger: "blur", message: "请输入用户账号" }],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ],
      },
      loading: false,
      captchaEnabled: true
    };
  },
  created() {
    this.getCode();
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.resetForm.uuid = res.uuid;
        }
      });
    },
    // 点击下一步
    handleNextStep() {
      this.$refs.resetForm.validate(valid => {
        if (valid) {
          this.loading = true;
          setUserInfo(this.resetForm).then(res => {
            this.$emit('handleNextStep')
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          })
        }
      });
    }
  }
};
</script>
